//
//  TJShareController.m
//  Teleport
//
//  Created by botu　 on 2020/8/8.
//  Copyright © 2020 byx. All rights reserved.
//

#import "TJShareController.h"
#import "TJShareCell.h"
#import "TJPosterView.h"
@interface TJShareController ()<UIGestureRecognizerDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
@property (weak, nonatomic) UIView *maskView;
@property (weak, nonatomic) UIView *contentView;

@property (strong, nonatomic) NSArray *datas;
@property (weak, nonatomic) UICollectionView *collectionView;
/**QRString */
@property (copy, nonatomic) NSString *QRString;

@end

@implementation TJShareController


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.modalPresentationStyle = UIModalPresentationCustom;
    }
    return self;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [UIView animateWithDuration:0.25 animations:^{
        self.maskView.backgroundColor = UIColor.tj_alertMaskColor;
        self.contentView.tj_y = KScreenHeight - self.contentView.tj_height;
    } completion:^(BOOL finished) {
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = UIColor.clearColor;
    
    UIView *maskView = [UIView tj_addToView:self.view];
    maskView.backgroundColor = [UIColor.tj_alertMaskColor colorWithAlphaComponent:0];
    maskView.frame = self.view.bounds;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didClickDismissButton)];
    [maskView addGestureRecognizer:tap];
    tap.delegate = self;
    UIView *contentView = [UIView tj_addToView:maskView];
    contentView.backgroundColor = UIColor.whiteColor;
    
    contentView.frame = CGRectMake(0, KScreenHeight, KScreenWidth, 300);
    
    [contentView drawRoundedWithByRoundingCorners:UIRectCornerTopRight | UIRectCornerTopLeft radius:10];
    
    UILabel *titleLabel = [UILabel lableWithSuperView:contentView font:MediumFont(17) color:UIColor.blackColor title:@"选择海报".localizedString textAlignment:NSTextAlignmentCenter];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.height.offset(40);
    }];
    
    
    UIButton *dismissButton = [UIButton buttonWithSuperView:contentView font:UIFont_Px(15) color:UIColor_Hex(0x272727) title:@"取消".localizedString];
    [dismissButton addTarget:self action:@selector(didClickDismissButton) forControlEvents:UIControlEventTouchUpInside];
    [dismissButton setContentHorizontalAlignment:(UIControlContentHorizontalAlignmentRight)];
    [dismissButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(titleLabel);
        make.width.height.offset(50);
        make.right.offset(-16);
    }];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    CGFloat height = contentView.tj_height*0.5;
    flowLayout.itemSize = CGSizeMake(height*0.8,height);
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 0);
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.dataSource = self;
    collectionView.delegate = self;
    [collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([TJShareCell class]) bundle:nil] forCellWithReuseIdentifier:@"cellid"];
    
    [contentView addSubview:collectionView];
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom);
        make.left.right.offset(0);
        make.height.offset(height);
    }];
    
    
    TJCellStyleModel *model = [TJCellStyleModel new];
    model.isSelect = NO;
    //image
    model.image = [UIImage imageNamed:@"poster1"];
    
    TJCellStyleModel *model1 = [TJCellStyleModel new];
    model1.isSelect = NO;
    //image
    model1.image = [UIImage imageNamed:@"poster2"];
    self.datas = @[model,model1];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self collectionView:self.collectionView didSelectItemAtIndexPath:indexPath];
    
    
    UIButton *saveButton = [UIButton buttonWithSuperView:contentView font:UIFont_Px(12) color:UIColor.blackColor title:@"保存".localizedString];
    
    [saveButton setImage:[UIImage imageNamed:@"user_save"] forState:UIControlStateNormal];
    [saveButton setImage:[UIImage imageNamed:@"user_save"] forState:UIControlStateHighlighted];
    [saveButton addTarget:self action:@selector(didClickSaveButton) forControlEvents:UIControlEventTouchUpInside];
    [saveButton setContentHorizontalAlignment:(UIControlContentHorizontalAlignmentCenter)];
    [saveButton setImagePosition:LXMImagePositionTop spacing:6];
    [saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(collectionView.mas_bottom).offset(10);
        make.width.offset(40);
        make.left.offset(16);
        make.height.offset(60);
    }];
    
    
    
    self.collectionView = collectionView;
    _maskView = maskView;
    _contentView = contentView;
    
    [self loadCodeMessage];
}
#pragma mark ---------------UICollectionViewDataSource, UICollectionViewDelegate------------------

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.datas.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    TJShareCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
    cell.model = self.datas[indexPath.row];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    TJCellStyleModel *cellModel = self.datas[indexPath.row];
    
    for (TJCellStyleModel *model in self.datas) {
        if (model == cellModel) {
            model.isSelect = YES;
        }else{
            model.isSelect = NO;
        }
    }
    [self.collectionView reloadData];
}

- (void)didClickSaveButton {
    //选中的图片
    UIImage *selectImage;
    for (TJCellStyleModel *model in self.datas) {
        if (model.isSelect) {
            selectImage = model.image;
        }
    }
    
    //生成二维码
    weakify(self)
    [Tools createQRWithString:self.QRString QRSize:CGSizeMake(ZOOM(80), ZOOM(80)) finishBlock:^(UIImage *image) {
        //生成海报
        TJPosterView *posterView = [[TJPosterView alloc] init];

        NSLog(@"%@",posterView);
        posterView.bgImageView.image = selectImage;
        posterView.codeImageView.image = image;
        //生成一张图片
        UIImage *finImage= [Tools snapshotSingleView:posterView];
        
        //保存本地
        
        [Tools saveImageToPhotos:finImage];
        
        [weakself didClickDismissButton];
        
    }];
    
    
    
}
- (void)didClickDismissButton {
    [self dismissComplete:nil];
}


- (void)dismissComplete:(void (^)(void))complete {
    
    [UIView animateWithDuration:0.25 animations:^{
        self.maskView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0];
        self.contentView.tj_y = KScreenHeight;
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:^{
            if (complete) complete();
        }];
    }];
}

- (void)loadCodeMessage {
    [self showloading];
    [TJNetworking.shareNetworking GET:@"member/member/code" parameters:@{@"memberId":TJUserInfo.readInfo.userId} success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
          [self hiddenloading];
        self.QRString = data[@"result"][@"quickMark"];
    } failure:^(NSError * _Nonnull error) {
          [self hiddenloading];
        
    }];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if (touch.view != self.maskView) {
        return NO;
    }else {
        return YES;
    }
}


@end
